﻿using System.Collections.Generic;
using ZeldoEngineObjects.Maps;
using ZeldoEngineObjects;

namespace ZeldoEngineServices.Maps
{
    public static class MapService
    {
        public static void SetTile(MapModel map, MapModel.Layer layer, int tileX, int tileY, uint value)
        {
            if (map.Tiles.ContainsKey(layer))
            {
                var tLayer = map.Tiles[layer];

                if (tileX <= tLayer.GetUpperBound(0) && tileY <= tLayer.GetUpperBound(1))
                {
                    tLayer[tileX, tileY] = value;
                }
            }
        }

        public static int? GetTile(MapModel map, MapModel.Layer layer, int x, int y)
        {
            if (map.Tiles.ContainsKey(layer) && (x >= 0 && x < map.Width) && (y >= 0 && y < map.Height))
            {
                return (int)(map.Tiles[layer][x, y] & 0xFFF);
            }

            return null;
        }

        public static uint? GetCompletTileInfos(MapModel map, MapModel.Layer layer, int x, int y)
        {
            if (map.Tiles.ContainsKey(layer) && (x >= 0 && x < map.Width) && (y >= 0 && y < map.Height))
            {
                return map.Tiles[layer][x, y];
            }

            return null;
        }

        public static void InitLevel(MapModel map, string mapName, int width, int height)
        {
            map.Tiles = new Dictionary<MapModel.Layer, uint[,]>();

            map.Label = mapName;
            map.Width = width;
            map.Height = height;

            for (var l = 0; l < 3; l++)
            {
                var layerTiles = new uint[map.Width, map.Height];

                for (var x = 0; x < map.Width; x++)
                {
                    for (var y = 0; y < map.Height; y++)
                    {
                        layerTiles[x, y] = (uint)(l == 0 ? 8 : 0);
                    }
                }

                map.Tiles.Add((MapModel.Layer)l, layerTiles);
            }
        }

        public static MapModel CreerCarte(string mapName, int width, int height, Chipset chipset)
        {
            var map = new MapModel();
            map.Chipset = chipset;

            InitLevel(map, mapName, width, height);

            return map;
        }
    }
}
